package app

import "github.com/sirupsen/logrus"

func MarkLatest(base string, version int64, codes ...*Chaincode) error {
	for _, c := range codes {
		c.Historic = false
		if version < 0 {
			c.Version = getVersionByHistoric(c.PackageId, c.Label, codes)
		} else {
			c.Version = uint64(version)
		}
		UpdateChaincode(c)
	}

	return nil
}

func getVersionByHistoric(pid string, label string, codes []*Chaincode) uint64 {
	var latest = uint64(0)
	for _, c := range codes {
		if c.Label == label && c.PackageId != pid {
			logrus.Infoln("获得历史版本", c.PackageId)
			if latest < c.Version {
				latest = c.Version
			}
		}
	}
	logrus.Infoln("最新版版本为", latest+1)
	return latest + 1
}
